package cn.niit.interceptor;

import cn.niit.entity.SysResource;
import cn.niit.entity.SysRoleResource;
import cn.niit.entity.SysUser;
import cn.niit.service.SysResourceService;
import cn.niit.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Component
public class MenuInterceptor implements HandlerInterceptor {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysResourceService  sysResourceService;

    /**
     * 用于拦截控制器方法的执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;  //返回true，放行所有的controller方法；

    }

    /**
     * 控制器方法执行之后，页面渲染之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("LoginInterceptor.postHandle++++++++++++++++++++++++++");
        // 第一步：获取用户请求URL
        /*String uri = request.getRequestURI();   //  /login
        String url = request.getRequestURL().toString();    // http://localhost:8080/SmartCampusMS/login
        System.out.println("uri: " + uri + " \t url:" + url);*/

        //获取登录信息
        String userCode = (String) SecurityUtils.getSubject().getPrincipal();
        //获取用户信息
        if (null == userCode){
            response.sendRedirect("/login");
        }else {
            SysUser sysUser = sysUserService.selectByUserCode(userCode);
            List<SysResource> menuList = sysResourceService.getMenuListByUserId(sysUser.getId());
            if(null == modelAndView){
                log.info("MenuInterceptor.postHandle ================ {} ============ modelAndView={}, menuList={}", request.getRequestURI(), modelAndView, menuList);
            }else{
                modelAndView.addObject("menuList", menuList);
            }
        }
    }
    /**
     * 处理完视图和模型数据，渲染视图完毕之后执行afterComplation()
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
